package com.yixun.qfbao.hander;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yixun.qfbao.api.service.ThirdPartyApiService;
import com.yixun.qfbao.apidto.GetWeiXinJsTicketReqDto;
import com.yixun.qfbao.apidto.GetWeiXinJsTicketResDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.util.MathUtil;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.utils.WeixinCommon;
import com.yixun.qfbao.vo.GetWeiXinJsTicketReqVo;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

/**
 * （3）	获取微信授权码
 * 
 * @author jzliu
 *		
 */
@Service("getWeiXinJsTicketHander")
public class GetWeiXinJsTicketHander extends CommonAbstractHander {

	private static final Logger logger = LoggerFactory.getLogger(GetWeiXinJsTicketHander.class);

	@Autowired
	private ThirdPartyApiService thirdPartyApiService;
	
	@Autowired
	private LoginUtils loginUtils;

	@Autowired
    private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;
	
	@SuppressWarnings("rawtypes")
	@Override
	public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
		GetWeiXinJsTicketReqVo req = (GetWeiXinJsTicketReqVo)reqDto;
		GetWeiXinJsTicketReqDto reqDto1 = req.getParams();
		BaseResponseDTO<GetWeiXinJsTicketResDto> res = new BaseResponseDTO<GetWeiXinJsTicketResDto>();
		GetWeiXinJsTicketResDto resDto = new GetWeiXinJsTicketResDto();
		try {
			//判断域名
			if(StringUtils.isBlank(reqDto1.getDomain()) && StringUtils.isBlank(reqDto1.getCompanyUuid())) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("未获取到域名!");
				res.setResData(resDto);
				res.setResult(resDto.getResult());
				return res;
			}
			//查询商户对应的微信appID和appSecret
			Map<String, String> map = thirdPartyApiService.getWeiXinAppid(reqDto1);
			if(map == null) {
				resDto.setResult(ResultEnum.FAIL.getNo());
				resDto.setResultMsg("商户对应的微信appID!");
				res.setResData(resDto);
				res.setResult(resDto.getResult());
				return res;
			}
			//微信js_ticket
			//从缓存读取js_ticket，读取不到时，调用微信接口获取新的js_ticket，并存入缓存
			String jsTicket = getTokenCache(reqDto1.getCompanyUuid());
			logger.info("jsTicket cache = " + jsTicket);
			if(jsTicket != null) {
			} else {
				reqDto1.setAppId(map.get("appId"));
				reqDto1.setAppSecret(map.get("appSecret"));
                String accessToken = wxAccessTokenCacheUtils.getAccessToken(reqDto1.getCompanyUuid(), SystemIdEnum.ASSISTANT.getCode(), reqDto1.getDomain());
				//查询商户对应的微信jsTicket
				Map<String,String> jsTicketMap = thirdPartyApiService.getWeiXinJsTicketByToken(accessToken);
				if(MapUtils.isEmpty(jsTicketMap)) {
					resDto.setResult(ResultEnum.FAIL.getNo());
					resDto.setResultMsg("获取微信js_ticket失败!");
					res.setResData(resDto);
					res.setResult(resDto.getResult());
					return res;
				}else{
					jsTicket = jsTicketMap.get("jsapi_ticket");
				}

				setTokenCache(reqDto1.getCompanyUuid(),jsTicketMap);
			}

			System.err.println("jsTicket==============================================>" +jsTicket);
			//随机码
			String noncestr = MathUtil.buildRandom(6) + "";
			//时间戳
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			//签名
			String signature = WeixinCommon
					.getSignature(jsTicket, timestamp, noncestr, reqDto1.getUrl());
			resDto.setAppid(map.get("appId"));
			resDto.setNoncestr(noncestr);
			resDto.setSignature(signature);
			resDto.setTime(timestamp);
			resDto.setCompanyUuid(map.get("companyUuid"));
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			logger.error("GetWeiXinJsTicketHander error: {}", e);
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("获取微信授权码失败!");
		}
		res.setResData(resDto);
		res.setResult(resDto.getResult());
		return res;
	}

	private	 String getTokenCache(String companyUuid){
		Map<String,String> map = new HashMap<>();
		Object cache =	loginUtils.get("access_token_key_" + companyUuid);
		Object token = RedisUtil.get(companyUuid+"_accessToken_"+SystemIdEnum.ASSISTANT.getCode());

		if(StringUtils.isEmpty(String.valueOf(token))){
		    //如果token缓存失效 则jsTicket所使用token失效
		    return null;
        }
		if(null == cache){
			return null;
		}
		map = (Map<String,String>)cache;
		if(!map.containsKey("jsapi_ticket") || StringUtils.isEmpty(map.get("jsapi_ticket"))){
			return null;
		}
		if(!map.containsKey("lost_time") || StringUtils.isEmpty(map.get("lost_time"))){
			return null;
		}
		String oldToken  = map.get("access_token");
		if(String.valueOf(token).equals(oldToken) ){
			return map.get("jsapi_ticket");
		}else{
			return null;
		}
	}

	private void setTokenCache(String companyUuid,Map<String,String> map){
		loginUtils.putJsTickeToken("access_token_key_" + companyUuid, map);
	}

}
